/**
 * Independent time operation tool to facilitate subsequent switch to dayjs
 */
import dayjs from 'dayjs';

const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss';
const DATE_FORMAT = 'YYYY-MM-DD';

export function formatToDateTime(
  date: dayjs.Dayjs | undefined = undefined,
  format = DATE_TIME_FORMAT,
): string | undefined {
  if (!date) return undefined;
  return dayjs(date).format(format);
}

export function formatToDate(
  date: dayjs.Dayjs | undefined = undefined,
  format = DATE_FORMAT,
): string | undefined {
  if (!date) return undefined;
  return dayjs(date).format(format);
}

/*
 * 将时间戳转化为 “几周前” 的形式
 */
export function getAgoAt(date) {
  if (!date) {
    return '';
  }
  const current_time = new Date().getTime() / 1000;
  const paramDate = Date.parse(date) / 1000;
  let diff = current_time - paramDate;
  let sign = '前';
  if (diff < 0) {
    diff = -1 * diff;
    sign = '后';
  }
  let agoAt = '刚刚';
  const timePoints = [
    { value: 60 * 60 * 24 * 365, suffix: '年' + sign, max: 2 },
    { value: 60 * 60 * 24 * 30, suffix: '月' + sign, max: 12 },
    { value: 60 * 60 * 24 * 7, suffix: '周' + sign, max: 4 },
    { value: 60 * 60 * 24, suffix: '天' + sign, max: 7 },
    { value: 60 * 60, suffix: '小时' + sign, max: 23 },
    { value: 60 * 10, suffix: '0分钟' + sign, max: 5 },
  ];
  for (let i = 0; i < timePoints.length; i++) {
    const point = timePoints[i];
    const mode = Math.floor(diff / point.value);
    if (mode >= 1) {
      agoAt = Math.min(mode, point.max) + point.suffix;
      break;
    }
  }
  return agoAt;
}

export const dateUtil = dayjs;
